
<!DOCTYPE html>
<html lang="zh-Hans" class="loading">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>redux学习之升级水果店面 - 默默默默燃</title>
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="google" content="notranslate" />
    <meta name="keywords" content="TriDiamond Obsidian,"> 
    <meta name="description" content="一枚前端搬砖队队员的记录册,优雅的处理 async action阿大通过请了一个采购员完成了耗时的进口商品的售卖。
但是，阿大同时也发现了一个问题：顾客要买水果生鲜的话需要找销售员，要买进口水果生鲜的话要找采购员，这样的话，顾,"> 
    <meta name="author" content="张白告丶"> 
    <link rel="alternative" href="atom.xml" title="默默默默燃" type="application/atom+xml"> 
    <link rel="icon" href="/img/favicon.png"> 
    <link href="https://fonts.loli.net/css?family=Roboto+Mono|Rubik&display=swap" rel="stylesheet">
    
<link rel="stylesheet" href="//at.alicdn.com/t/font_1429596_nzgqgvnmkjb.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/animate.css/3.7.2/animate.min.css">

    
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/css/share.min.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/codemirror/5.48.4/codemirror.min.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/codemirror/5.48.4/theme/dracula.css">

    
<link rel="stylesheet" href="/css/obsidian.css">

    
<link rel="stylesheet" href="/css/ball-atom.min.css">

<meta name="generator" content="Hexo 4.2.0"></head>


<body class="loading">
    <div class="loader">
        <div class="la-ball-atom la-2x">
            <div></div>
            <div></div>
            <div></div>
            <div></div>
        </div>
    </div>
    <span id="config-title" style="display:none">默默默默燃</span>
    <div id="loader"></div>
    <div id="single">
    <div class="scrollbar gradient-bg-rev"></div>
<div id="top" style="display: block;">
    <div class="bar" style="width: 0;"></div>
    <div class="navigation animated fadeIn fast delay-1s">
        <img id="home-icon" class="icon-home" src="/img/favicon.png" alt="" data-url="https://zhanghao-web.github.io">
        <div id="play-icon" title="Play/Pause" class="iconfont icon-play"></div>
        <h3 class="subtitle">redux学习之升级水果店面</h3>
        <div class="social">
            <!--        <div class="like-icon">-->
            <!--            <a href="javascript:;" class="likeThis active"><span class="icon-like"></span><span class="count">76</span></a>-->
            <!--        </div>-->
            <div>
                <div class="share">
                    
                        <a href="javascript:;" class="iconfont icon-share1"></a>
                        <div class="share-component-cc" data-disabled="facebook,douban,linkedin,diandian,tencent,google"></div>
                    
                </div>
            </div>
        </div>
    </div>
</div>

    <div class="section">
        <div class=article-header-wrapper>
    <div class="article-header">
        <div class="article-cover animated fadeIn" style="
            animation-delay: 600ms;
            animation-duration: 1.2s;
            background-image: 
                radial-gradient(ellipse closest-side, rgba(0, 0, 0, 0.65), #100e17),
                url(/img/cover.jpg) ">
        </div>
        <div class="else">
            <p class="animated fadeInDown">
                
                <a href="/categories/Redux"><b>「
                    </b>REDUX<b> 」</b></a>
                
                April 25, 2018
            </p>
            <h3 class="post-title animated fadeInDown"><a href="/2018/04/25/React/Redux/redux%E5%AD%A6%E4%B9%A0%E4%B9%8B%E5%8D%87%E7%BA%A7%E6%B0%B4%E6%9E%9C%E5%BA%97%E9%9D%A2/" title="redux学习之升级水果店面" class="">redux学习之升级水果店面</a>
            </h3>
            
            <p class="post-count animated fadeInDown">
                
                <span>
                    <b class="iconfont icon-text2"></b> <i>Words count</i>
                    20k
                </span>
                
                
                <span>
                    <b class="iconfont icon-timer__s"></b> <i>Reading time</i>
                    18 mins.
                </span>
                
                
                
                <span id="busuanzi_container_page_pv">
                    <b class="iconfont icon-read"></b> <i>Read count</i>
                    <span id="busuanzi_value_page_pv">0</span>
                </span>
                
            </p>
            
            
            <ul class="animated fadeInDown post-tags-list" itemprop="keywords"><li class="animated fadeInDown post-tags-list-item"><a class="animated fadeInDown post-tags-list-link" href="/tags/Redux/" rel="tag">Redux</a></li></ul>
            
        </div>
    </div>
</div>

<div class="screen-gradient-after">
    <div class="screen-gradient-content">
        <div class="screen-gradient-content-inside">
            <div class="bold-underline-links screen-gradient-sponsor">
                <p>
                    <span class="animated fadeIn delay-1s"></span>
                </p>
            </div>
        </div>
    </div>
</div>

<div class="article">
    <div class='main'>
        <div class="content markdown animated fadeIn">
            <h2 id="优雅的处理-async-action"><a href="#优雅的处理-async-action" class="headerlink" title="优雅的处理 async action"></a>优雅的处理 async action</h2><p>阿大通过请了一个采购员完成了耗时的进口商品的售卖。</p>
<p>但是，阿大同时也发现了一个问题：顾客要买水果生鲜的话需要找<strong>销售员</strong>，要买进口水果生鲜的话要找<strong>采购员</strong>，这样的话，顾客需要找不同的人，很麻烦。阿大想了想，能不能让顾客只找<strong>销售员</strong>，然后<strong>销售员</strong>如果有需求再找<strong>采购员</strong>采购呢。</p>
<p>阿大想到了办法，让<strong>销售员</strong>把所有的需求都告诉采购员，然后<strong>采购员</strong>再传递给<strong>收银员</strong>，这样，如果是需要采购的水果生鲜，就可以独自去处理了，这样就需要把<strong>采购员</strong>改成这样了：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> API = <span class="function"><span class="params">store</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="comment">// 和 收银员 对接的方式</span></span><br><span class="line">  <span class="keyword">const</span> next = store.dispatch;</span><br><span class="line">  <span class="comment">// 接管销售员传来的顾客需求</span></span><br><span class="line">  store.dispatch = <span class="function"><span class="params">action</span> =&gt;</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 处理完了之后再对接 收银员</span></span><br><span class="line">    <span class="keyword">switch</span> (action.type) &#123;</span><br><span class="line">      <span class="keyword">case</span> <span class="string">'BUY_IMPORTED_APPLE'</span>: fetching(<span class="number">2000</span>, () =&gt; next(action)); <span class="keyword">break</span>;</span><br><span class="line">      <span class="keyword">case</span> <span class="string">'BUY_IMPORTED_EGG'</span>: fetching(<span class="number">3000</span>, () =&gt; next(action)); <span class="keyword">break</span>;</span><br><span class="line">      <span class="keyword">default</span>: next(action);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">API(store);</span><br></pre></td></tr></table></figure>
<p>然后顾客来了之后就都只用找销售员了：<br><a id="more"></a></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">store.dispatch(buyApple(<span class="number">3</span>));</span><br><span class="line">store.dispatch(buyImportedApple(<span class="number">10</span>));</span><br><span class="line">store.dispatch(buyEgg(<span class="number">1</span>));</span><br><span class="line">store.dispatch(buyImportedEgg(<span class="number">10</span>));</span><br><span class="line">store.dispatch(buyApple(<span class="number">4</span>));</span><br><span class="line">store.dispatch(buyImportedApple(<span class="number">10</span>));</span><br><span class="line">store.dispatch(buyEgg(<span class="number">8</span>));</span><br><span class="line">store.dispatch(buyImportedEgg(<span class="number">10</span>));</span><br><span class="line"><span class="comment">// &#123;"fruit":&#123;"apple":3,"importedApple":0&#125;,"fresh":&#123;"egg":0,"importedEgg":0&#125;&#125;</span></span><br><span class="line"><span class="comment">// &#123;"fruit":&#123;"apple":3,"importedApple":0&#125;,"fresh":&#123;"egg":1,"importedEgg":0&#125;&#125;</span></span><br><span class="line"><span class="comment">// &#123;"fruit":&#123;"apple":7,"importedApple":0&#125;,"fresh":&#123;"egg":1,"importedEgg":0&#125;&#125;</span></span><br><span class="line"><span class="comment">// &#123;"fruit":&#123;"apple":7,"importedApple":0&#125;,"fresh":&#123;"egg":9,"importedEgg":0&#125;&#125;</span></span><br><span class="line"><span class="comment">// &#123;"fruit":&#123;"apple":7,"importedApple":10&#125;,"fresh":&#123;"egg":9,"importedEgg":0&#125;&#125;</span></span><br><span class="line"><span class="comment">// &#123;"fruit":&#123;"apple":7,"importedApple":20&#125;,"fresh":&#123;"egg":9,"importedEgg":0&#125;&#125;</span></span><br><span class="line"><span class="comment">// &#123;"fruit":&#123;"apple":7,"importedApple":20&#125;,"fresh":&#123;"egg":9,"importedEgg":10&#125;&#125;</span></span><br><span class="line"><span class="comment">// &#123;"fruit":&#123;"apple":7,"importedApple":20&#125;,"fresh":&#123;"egg":9,"importedEgg":20&#125;&#125;</span></span><br></pre></td></tr></table></figure>
<h3 id="图解"><a href="#图解" class="headerlink" title="图解"></a>图解</h3><p><img src="https://user-gold-cdn.xitu.io/2018/4/20/162e3327a35fb0a4?imageView2/0/w/1280/h/960/format/webp/ignore-error/1" alt="asyncAction"></p>
<h2 id="编写和使用中间件"><a href="#编写和使用中间件" class="headerlink" title="编写和使用中间件"></a>编写和使用中间件</h2><p>阿大通过改善流程对接完成了水果店的升级。</p>
<p>但是阿大又有一个新的想法，他想详细的看看每一个顾客的<code>购买需求</code>来了之后，账本的前后变化。看来又要加一个新角色<strong>记录员</strong>了。难道要像加采购员那样手动的一个个的加吗？那可太麻烦了。正好阿大发现 redux 里有一个功能就是<strong>中间件</strong>。中间件是干嘛的呢？简而言之，就是把顾客的需求从销售员到收银员之间加上各种角色来处理。每一个角色就是一个中间件。接下来阿大就开始来写中间件了。</p>
<p>redux 中间件写起来其实很简单，就是一个函数而已。按照它的要求。这个函数接受一个<strong>{ dispatch, getState }</strong>对象作为参数，然后返回一个 <strong>action</strong></p>
<p>那这样，就可以把原来的<code>采购员也改造成中间件</code>了，其实采购员就是拿到了顾客需求之后让顾客的需求延迟 <strong>dispatch</strong>，这用<code>延迟用函数</code>就可以做到了:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// next 是用中间件增强之后的 dispatch</span></span><br><span class="line"><span class="comment">// dispatch 是最原始的 store.dispatch</span></span><br><span class="line"><span class="keyword">const</span> thunkMiddleware = <span class="function">(<span class="params">&#123; dispatch &#125;</span>) =&gt;</span> <span class="function"><span class="params">next</span> =&gt;</span> <span class="function"><span class="params">action</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">typeof</span> action === <span class="string">'function'</span>) &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 函数形式的 action 就把 dispatch 给这个 action，让 action 决定什么时候 dispatch （控制反转）</span></span><br><span class="line">    <span class="keyword">return</span> action(dispatch);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 普通的 action 就直接传递给下一个中间件处理</span></span><br><span class="line">  <span class="keyword">return</span> next(action);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>然后我们就需要把原来的顾客需求改一下了：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 买水果 - 进口苹果</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">buyImportedApple</span>(<span class="params">num</span>) </span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 返回一个函数类型的 action，这个函数接受 dispatch，可以决定什么时候 dispatch</span></span><br><span class="line">  <span class="keyword">return</span> <span class="function"><span class="params">dispatch</span> =&gt;</span> API.fetchImportedApple(<span class="function"><span class="params">()</span> =&gt;</span> dispatch(&#123;</span><br><span class="line">    type: <span class="string">'BUY_IMPORTED_APPLE'</span>,</span><br><span class="line">    payload: num</span><br><span class="line">  &#125;));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 买生鲜 - 进口鸡蛋</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">buyImportedEgg</span>(<span class="params">num</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="function"><span class="params">dispatch</span> =&gt;</span> API.fetchImportedEgg(<span class="function"><span class="params">()</span> =&gt;</span> dispatch(&#123;</span><br><span class="line">    type: <span class="string">'BUY_IMPORTED_EGG'</span>,</span><br><span class="line">    payload: num</span><br><span class="line">  &#125;));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>然后<code>采购员</code>就可以只负责采购了，改回去：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 采购商品生成器，不同的商品需要不同的时间采购</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">fetching</span>(<span class="params">time, callback</span>) </span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 用延时模拟采购时间</span></span><br><span class="line">  <span class="keyword">const</span> timer = setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    clearTimeout(timer);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 采购完成，通知销售员</span></span><br><span class="line">    callback();</span><br><span class="line">  &#125;, time);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 采购进口苹果需要 2 天（2s）</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">fetchImportedApple</span>(<span class="params">callback</span>) </span>&#123;</span><br><span class="line">  fetching(<span class="number">2000</span>, callback);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 采购进口苹果需要 3 天（3s）</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">fetchImportedEgg</span>(<span class="params">callback</span>) </span>&#123;</span><br><span class="line">  fetching(<span class="number">3000</span>, callback);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 采购员</span></span><br><span class="line"><span class="keyword">const</span> API = &#123;</span><br><span class="line">  fetchImportedApple, <span class="comment">// 采购进口苹果</span></span><br><span class="line">  fetchImportedEgg <span class="comment">// 采购进口鸡蛋</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>然后，我们在添加一个<code>记录员</code>的中间件：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> loggerMiddleware = <span class="function">(<span class="params">&#123; getState &#125;</span>) =&gt;</span> <span class="function"><span class="params">next</span> =&gt;</span> <span class="function"><span class="params">action</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">`state before: <span class="subst">$&#123;<span class="built_in">JSON</span>.stringify(getState())&#125;</span>`</span>);</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">`action: <span class="subst">$&#123;<span class="built_in">JSON</span>.stringify(action)&#125;</span>`</span>);</span><br><span class="line">  <span class="keyword">const</span> result = next(action);</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">`state after: <span class="subst">$&#123;<span class="built_in">JSON</span>.stringify(getState())&#125;</span>`</span>);</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'================================================'</span>);</span><br><span class="line">  <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>删除掉原来的监听：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//- store.subscribe(() =&gt; console.log(JSON.stringify(store.getState())));</span></span><br></pre></td></tr></table></figure>
<p>好了，接下来就可以通过 redux 的 <strong>applyMiddleware</strong> 来串联起这些中间件啦。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> &#123; createStore, combineReducers, applyMiddleware &#125; = <span class="built_in">require</span>(<span class="string">'redux'</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 中间件的调用顺序是从右到左</span></span><br><span class="line"><span class="keyword">const</span> store = createStore(reducer, applyMiddleware(thunkMiddleware, loggerMiddleware));</span><br></pre></td></tr></table></figure>
<p>好了，大功告成，开始服务顾客：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">store.dispatch(buyApple(<span class="number">3</span>));</span><br><span class="line">store.dispatch(buyImportedApple(<span class="number">10</span>));</span><br><span class="line"></span><br><span class="line"><span class="comment">// state before: &#123;"fruit":&#123;"apple":0,"importedApple":0&#125;,"fresh":&#123;"egg":0,"importedEgg":0&#125;&#125;</span></span><br><span class="line"><span class="comment">// action: &#123;"type":"BUY_APPLE","payload":3&#125;</span></span><br><span class="line"><span class="comment">// state after: &#123;"fruit":&#123;"apple":3,"importedApple":0&#125;,"fresh":&#123;"egg":0,"importedEgg":0&#125;&#125;</span></span><br><span class="line"><span class="comment">// ================================================</span></span><br><span class="line"><span class="comment">// state before: &#123;"fruit":&#123;"apple":3,"importedApple":0&#125;,"fresh":&#123;"egg":0,"importedEgg":0&#125;&#125;</span></span><br><span class="line"><span class="comment">// action: &#123;"type":"BUY_EGG","payload":1&#125;</span></span><br><span class="line"><span class="comment">// state after: &#123;"fruit":&#123;"apple":3,"importedApple":0&#125;,"fresh":&#123;"egg":1,"importedEgg":0&#125;&#125;</span></span><br><span class="line"><span class="comment">// ================================================</span></span><br></pre></td></tr></table></figure>
<p>上面我们写的两个中间件其实就是 <code>redux-thunk</code> 和 <code>redux-logger</code> 的简版。在实际中，推荐使用它们，会更可信。</p>
<h3 id="图解-1"><a href="#图解-1" class="headerlink" title="图解"></a>图解</h3><p><img src="https://user-gold-cdn.xitu.io/2018/4/23/162f0a03fc97dbca?imageView2/0/w/1280/h/960/format/webp/ignore-error/1" alt="redux-chunk"></p>
<p>编写 redux 中间件需要按照要求来，返回这样的函数</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 中间件接受一个对象，里面有原始的 dispatch，和 getState 方法用于获取 state</span></span><br><span class="line"><span class="comment">// 中间件函数返回一个函数，这个函数接受一个 next 参数，这个 next 是下一个中间件要做的事情 action =&gt; &#123; ... &#125;</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">thunkMiddleware</span>(<span class="params">&#123; dispatch, getState &#125;</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params">next</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params">action</span>) </span>&#123;</span><br><span class="line">      <span class="comment">// 做你的事情</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><a href="https://juejin.im/user/57d8a928d203090069c13a21/likes" target="_blank" rel="noopener">原文地址</a></p>

            <!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->
            <audio id="audio" loop="1" preload="auto" controls="controls"
                data-autoplay="false">
                <source type="audio/mpeg" src="">
            </audio>
            
            <ul id="audio-list" style="display:none">
                
                
                <li title='0' data-url='/statics/chengdu.mp3'></li>
                
                    
            </ul>
            
            
            
    <div id='gitalk-container' class="comment link"
        data-ae='true'
        data-ci='ec894e2b66f752e8b7fb'
        data-cs='3ccc2e92bb350688fe2c2dc2930189b62622bfb1'
        data-r='blog-comments'
        data-o='TriDiamond'
        data-a='TriDiamond'
        data-d='undefined'
    >Comments</div>


            
            
        </div>
        <div class="sidebar">
            <div class="box animated fadeInRight">
                <div class="subbox">
                    <img src="https://res.cloudinary.com/tridiamond/image/upload/v1573019751/TriDiamond_logo_ui_xeublz.jpg" height=300 width=300></img>
                    <p>张白告丶</p>
                    <span>Think like an artist, develop like an artisan</span>
                    <dl>
                        <dd><a href="https://github.com/zhanghao-web" target="_blank"><span
                                    class=" iconfont icon-github"></span></a></dd>
                        <dd><a href="" target="_blank"><span
                                    class=" iconfont icon-twitter"></span></a></dd>
                        <dd><a href="" target="_blank"><span
                                    class=" iconfont icon-stack-overflow"></span></a></dd>
                    </dl>
                </div>
                <ul>
                    <li><a href="/">149 <p>Articles</p></a></li>
                    <li><a href="/categories">23 <p>Categories</p></a></li>
                    <li><a href="/tags">47 <p>Tags</p></a></li>
                </ul>
            </div>
            
            
            
            <div class="box sticky animated fadeInRight faster">
                <div id="toc" class="subbox">
                    <h4>Contents</h4>
                    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#优雅的处理-async-action"><span class="toc-number">1.</span> <span class="toc-text">优雅的处理 async action</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#图解"><span class="toc-number">1.1.</span> <span class="toc-text">图解</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#编写和使用中间件"><span class="toc-number">2.</span> <span class="toc-text">编写和使用中间件</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#图解-1"><span class="toc-number">2.1.</span> <span class="toc-text">图解</span></a></li></ol></li></ol>
                </div>
            </div>
            
            
        </div>
    </div>
</div>

    </div>
</div>
    <div id="back-to-top" class="animated fadeIn faster">
        <div class="flow"></div>
        <span class="percentage animated fadeIn faster">0%</span>
        <span class="iconfont icon-top02 animated fadeIn faster"></span>
    </div>
</body>
<footer>
    <p class="copyright" id="copyright">
        &copy; 2020
        <span class="gradient-text">
            张白告丶
        </span>.
        Powered by <a href="http://hexo.io/" title="Hexo" target="_blank" rel="noopener">Hexo</a>
        Theme
        <span class="gradient-text">
            <a href="https://github.com/TriDiamond/hexo-theme-obsidian" title="Obsidian" target="_blank" rel="noopener">Obsidian</a>
        </span>
        <small><a href="https://github.com/TriDiamond/hexo-theme-obsidian/blob/master/CHANGELOG.md" title="v1.4.3" target="_blank" rel="noopener">v1.4.3</a></small>
    </p>
</footer>

<script type="text/javascript" src="https://cdn.bootcss.com/mathjax/2.7.6/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<script>
  MathJax.Hub.Config({
    "HTML-CSS": {
      preferredFont: "TeX",
      availableFonts: ["STIX", "TeX"],
      linebreaks: {
        automatic: true
      },
      EqnChunk: (MathJax.Hub.Browser.isMobile ? 10 : 50)
    },
    tex2jax: {
      inlineMath: [
        ["$", "$"],
        ["\\(", "\\)"]
      ],
      processEscapes: true,
      ignoreClass: "tex2jax_ignore|dno",
      skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    },
    TeX: {
      noUndefined: {
        attributes: {
          mathcolor: "red",
          mathbackground: "#FFEEEE",
          mathsize: "90%"
        }
      },
      Macros: {
        href: "{}"
      }
    },
    messageStyle: "none"
  });
</script>
<script>
  function initialMathJax() {
    MathJax.Hub.Queue(function () {
      var all = MathJax.Hub.getAllJax(),
        i;
      // console.log(all);
      for (i = 0; i < all.length; i += 1) {
        console.log(all[i].SourceElement().parentNode)
        all[i].SourceElement().parentNode.className += ' has-jax';
      }
    });
  }

  function reprocessMathJax() {
    if (typeof MathJax !== 'undefined') {
      MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
    }
  }
</script>



    
<link rel="stylesheet" href="//cdn.bootcss.com/gitalk/1.5.0/gitalk.min.css">

    
<script src="//cdn.bootcss.com/gitalk/1.5.0/gitalk.min.js"></script>



<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="/js/plugin.js"></script>
<script src="/js/obsidian.js"></script>
<script src="/js/jquery.truncate.js"></script>
<script src="/js/search.js"></script>


<script src="//cdn.bootcss.com/typed.js/2.0.10/typed.min.js"></script>


<script src="//cdn.bootcss.com/blueimp-md5/2.12.0/js/md5.min.js"></script>


<script src="//cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/js/social-share.min.js"></script>


<script src="https://cdn.bootcss.com/codemirror/5.48.4/codemirror.min.js"></script>

    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/javascript/javascript.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/css/css.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/xml/xml.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/htmlmixed/htmlmixed.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/clike/clike.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/php/php.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/shell/shell.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/python/python.min.js"></script>




    
<script src="/js/busuanzi.min.js"></script>

    <script>
        $(document).ready(function () {
            if ($('span[id^="busuanzi_"]').length) {
                initialBusuanzi();
            }
        });
    </script>



<link rel="stylesheet" href="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe.min.css">
<link rel="stylesheet" href="//cdn.bootcss.com/photoswipe/4.1.3/default-skin/default-skin.min.css">


<script src="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe.min.js"></script>
<script src="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe-ui-default.min.js"></script>


<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>
    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">
        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>
        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">
            <div class="pswp__top-bar">
                <!--  Controls are self-explanatory. Order can be changed. -->
                <div class="pswp__counter"></div>
                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
                <button class="pswp__button pswp__button--share" title="Share"></button>
                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                      <div class="pswp__preloader__cut">
                        <div class="pswp__preloader__donut"></div>
                      </div>
                    </div>
                </div>
            </div>
            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div> 
            </div>
            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>
            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>
            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>
        </div>
    </div>
</div>



    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="//www.googletagmanager.com/gtag/js?id=UA-149874671-1"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());

        gtag('config', 'UA-149874671-1');
    </script>





<script>
    function initialTyped () {
        var typedTextEl = $('.typed-text');
        if (typedTextEl && typedTextEl.length > 0) {
            var typed = new Typed('.typed-text', {
                strings: ["Think like an artist, develop like an artisan", "艺术家思维去思考问题，工匠创造精神去开发"],
                typeSpeed: 90,
                loop: true,
                loopCount: Infinity,
                backSpeed: 20,
            });
        }
    }

    if ($('.article-header') && $('.article-header').length) {
        $(document).ready(function () {
            initialTyped();
        });
    }
</script>




</html>
